<template>
    <view>
        <hj-loading :show="isInitLoad" v-if="isInitLoad" />
        <view class="page over-auto-y column" v-else>
            <hj-navbar title="确认订单" />
            <!-- 内容区 -->
            <view class="flex-auto w100 over-auto-y p-30">
                <!-- 订房信息 -->
                <RoomInfo :info="roomInfo" />
                <!-- 用户信息 -->
                <UserInfo
                    :form="form"
                    :info="roomInfo"
                    @update:form="form = $event"
                    @change="handleChange"
                    :validateForm="validateForm"
                    @update:validateForm="validateForm = $event"
                />
                <PolicyService :info="roomInfo" />
            </view>
            <!-- 底部 -->
            <PreFooter :info="roomInfo" @submit="submit" :roomNum="roomNum" />
        </view>
    </view>
</template>

<script setup>
/**
 * @description 预下单页面
 * @author yinzhi
 * @date 2025-05
 */
import { onLoad } from '@dcloudio/uni-app'
import { ref, defineComponent, computed } from 'vue'
import { test } from '@/uni_modules/uview-plus'
import { logger } from '@/utils/log.js'
import PreFooter from './components/PreFooter.vue'
import RoomInfo from './components/RoomInfo.vue'
import UserInfo from './components/UserInfo.vue'
import PolicyService from './components/PolicyService.vue'
import { getRoomDetailApi } from '@/libs/api/roomApi.js'
import { getCreateOrderApi, getPayOrderApi } from '@/libs/api/orderApi.js'
import { useStore } from 'vuex'
const store = useStore()
// 引入组件
defineComponent({
    components: {
        PreFooter,
        RoomInfo,
        UserInfo,
        PolicyService
    }
})
// 入住信息
const checkInInfo = computed(() => store.state.platform.checkInInfo || '')
const roomNum = ref(checkInInfo.value.roomAmount || 1)
// 酒店信息
const hotelInfo = computed(() => store.state.platform.hotelInfo || '')
const userInfo = computed(() => store.state.platform.userInfo || '')
// 房型ID
const roomId = ref()
// 初始化加载
const isInitLoad = ref(true)
// 表单内容
const form = ref({
    name: '',
    phone: '',
    arrivalTime: ''
})
// 表单错误提示
const validateForm = ref({
    nameTips: '',
    phoneTips: ''
})
// 是否还能点击
const isAllowClick = ref(true)

// 房型数据
const roomInfo = ref({
    name: '',
    imageLists: [], //相册列表
    facilityService: {}, //设施服务
    hotelPolicy: {}, //酒店政策
    roomTypeInfoDetailResp: {}, //房型相关信息
    hotelRoomFacilityResp: {}, //房型设施
    roomInfoPriceResp: {} //房间价格明细
})

onLoad(async options => {
    isAllowClick.value = true
    form.value.phone = userInfo.value.mobile
    if (options.roomId) {
        roomId.value = options.roomId
        await getRoomDetails()
    } else {
        isInitLoad.value = false
    }
})
// 提示次数,防止提示重复出现多次
const tipsCount = ref(0)
// 获取房型详情
const getRoomDetails = async () => {
    if (!roomId.value || !roomNum.value) return
    try {
        const data = await getRoomDetailApi({
            checkInDate: checkInInfo.value.startDate,
            checkOutDate: checkInInfo.value.endDate,
            hotelId: hotelInfo.value.id,
            roomId: roomId.value,
            roomNum: roomNum.value
        })
        roomInfo.value = data || {}
        isInitLoad.value = false
        const roomAmount = checkInInfo.value?.roomAmount || 1
        const stockNum = data.roomTypeInfoDetailResp?.stockNum || 1
        if (roomAmount > stockNum && tipsCount.value <= 0) {
            tipsCount.value++
            uni.showModal({
                title: '库存不足',
                content: `房型只剩${stockNum}间房，是否继续下单？继续下单最多只能下单${stockNum}间房`,
                confirmColor: '#da8c10',
                confirmText: '继续下单',
                cancelColor: '#999999',
                success: res => {
                    if (res.cancel) {
                        uni.navigateBack({
                            delta: 1
                        })
                    }
                }
            })
        }
    } catch (error) {
        isInitLoad.value = false
        logger.error('[getRoomDetails] 获取房型详情失败: ', error)
    }
}

const handleChange = e => {
    roomNum.value = e.value
    getRoomDetails()
}

const requestPayment = data => {
    // 调起 微信支付
    uni.requestPayment({
        timeStamp: data.timeStamp,
        nonceStr: data.nonceStr,
        package: data.packageValue,
        signType: data.signType,
        paySign: data.paySign,
        success: res => {
            uni.showToast({
                title: '支付成功',
                icon: 'none',
                mask: true
            })
            let time = setTimeout(() => {
                uni.redirectTo({
                    url: `/pages/order/order-list/index`
                })
                clearTimeout(time)
            }, 1000)
        },
        fail: err => {
            uni.showToast({
                title: '取消支付',
                icon: 'none',
                mask: true
            })
            let time = setTimeout(() => {
                uni.redirectTo({
                    url: `/pages/order/order-list/index`
                })
                clearTimeout(time)
            }, 1000)
        }
    })
}

// 立即支付
const payOrder = async orderNo => {
    try {
        const data = await getPayOrderApi({
            orderNo: orderNo,
            payBizType: 1, //1: 订单支付
            payWay: 1 //1: 微信支付
        })
        await requestPayment(data)
    } catch (error) {
        isAllowClick.value = true
        logger.error('[getPayOrderApi] 唤起支付失败: ', error)
    }
}

// 提交订单 提交之前先判断用户信息是否填写完成
// 1. 姓名 2. 手机号
const submit = async () => {
    if (form.value.name === '') {
        validateForm.value.nameTips = '请填写住客姓名'
    } else if (!test.chinese(form.value.name) || form.value.name.length < 2) {
        validateForm.value.nameTips = '请填写正确的姓名'
    }
    if (form.value.phone === '') {
        validateForm.value.phoneTips = '请填写手机号'
    } else if (!test.mobile(form.value.phone)) {
        validateForm.value.phoneTips = '请填写正确的手机号'
    }
    // 使用 Object.values 和 some 方法判断是否有验证信息不为空
    if (Object.values(validateForm.value).some(value => value)) {
        return
    }
    if (!isAllowClick.value) {
        return
    }
    isAllowClick.value = false
    try {
        const data = await getCreateOrderApi({
            arrivalStartTime: form.value.arrivalTime,
            checkInDate: checkInInfo.value.startDate,
            checkOutDate: checkInInfo.value.endDate,
            contactName: form.value.name,
            contactPhone: form.value.phone,
            guestCount: checkInInfo.value.adult,
            hotelId: hotelInfo.value.id,
            roomId: roomId.value,
            roomNum: roomNum.value,
            isExtendedOrder: false
        })
        if (data.orderSuccess) {
            await payOrder(data.orderNo)
        } else {
            isAllowClick.value = true
            uni.showToast({
                title: data.errorMsg,
                icon: 'none',
                mask: true
            })
        }
    } catch (error) {
        isAllowClick.value = true
        logger.error('[getCreateOrderApi] 下单失败: ', error)
    }
}
</script>

<style scoped lang="scss">
:deep(.u-input) {
    padding-left: 0 !important;
    padding-right: 0 !important;
}
.page {
    background: $uni-bg-color-grey;
    width: 100vw;
    min-height: 100vh;
}
</style>
